package cc.z8g.browser.utils;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.Transformation;
import android.webkit.PermissionRequest;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.view.animation.PathInterpolatorCompat;

import java.io.File;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

public final class MiscUtils {

    private static final String TAG = "MiscUtils";

    /** 是否支持完全匿名模式 */
    public static final boolean FULL_INCOGNITO = Build.VERSION.SDK_INT >= 28;
    /** 在页面加载时对文本重新排列（Reflow）以适应屏幕宽度。具体来说，代码的功能是将页面中 body 元素的宽度设置为当前窗口的宽度，从而实现文本根据窗口大小自适应调整布局 */
    public static final String TextReflow = "(function(){'use strict';document.getElementsByTagName('body')[0].style.width=window.innerWidth+'px';}());";

    private MiscUtils() {
    }

    /** Converts Density Pixels (DP) to Pixels (PX). */
    public static int dpToPx(float dp) {
        DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
        return (int) (dp * metrics.density + 0.5f);
    }

    public static void trimCache(@NonNull Context context) {
        try {
            File dir = context.getCacheDir();

            if (dir != null && dir.isDirectory()) {
                FileUtils.deleteDir(dir);
            }
        } catch (Exception ignored) {

        }
    }

    public static boolean isColorGrayscale(int pixel) {
        int alpha = (pixel & 0xFF000000) >> 24;
        int red = (pixel & 0x00FF0000) >> 16;
        int green = (pixel & 0x0000FF00) >> 8;
        int blue = (pixel & 0x000000FF);

        return red == green && green == blue;

    }

    @Nullable
    public static String guessFileExtension(@NonNull String filename) {
        int lastIndex = filename.lastIndexOf('.') + 1;
        if (lastIndex > 0 && filename.length() > lastIndex) {
            return filename.substring(lastIndex);
        }
        return null;
    }

    /** 创建一个平滑的贝塞尔曲线插值器。 */
    public static Interpolator createInterpolation() {
        return new Interpolator() {
            private final Interpolator interpolator = PathInterpolatorCompat.create(0.25f, 0.1f, 0.25f, 1f);

            @Override
            public float getInterpolation(final float input) {
                return interpolator.getInterpolation(input);
            }
        };
    }

    /**
     * Gets the width of the device's screen.
     *
     * @param context the context used to access the [WindowManager].
     */
    public static int getScreenWidth(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Point point = new Point();
        windowManager.getDefaultDisplay().getSize(point);
        return point.x;
    }

    @Nullable
    public static String getFileName(@NonNull ContentResolver contentResolver, @NonNull Uri uri) {
        Cursor metaCursor = contentResolver.query(uri, new String[]{MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
        if (metaCursor != null) {
            try {
                if (metaCursor.moveToFirst()) {
                    return metaCursor.getString(0);
                }
            } finally {
                FileUtils.close(metaCursor);
            }
        }
        return null;
    }

    /** 获取所需申请的权限列表 */
    public static Set<String> getRequiredPermissionSet(@NonNull android.webkit.PermissionRequest request) {
        String[] resArr = request.getResources();
        if (resArr == null || resArr.length == 0) {
            return Collections.emptySet();
        }
        Set<String> result = new HashSet<>();
        for (int i = 0; i < resArr.length; i++) {
            String res = resArr[i];
            if (PermissionRequest.RESOURCE_AUDIO_CAPTURE.equals(res)) {
                result.add(Manifest.permission.RECORD_AUDIO);
                result.add(Manifest.permission.MODIFY_AUDIO_SETTINGS);
            } else if (PermissionRequest.RESOURCE_VIDEO_CAPTURE.equals(res)) {
                result.add(Manifest.permission.CAMERA);
            }
            // PermissionRequest.RESOURCE_MIDI_SYSEX
            // PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID
        }
        return result;
    }

    public static void showToast(@NonNull Context context, @StringRes int resource) {
        ThreadPool.postUI(() -> {
            Toast.makeText(context, resource, Toast.LENGTH_SHORT).show();
        });
    }

    public static void showToast(@NonNull Context context, @NonNull String message) {
        ThreadPool.postUI(() -> {
            Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        });
    }
}
